package jude.java.money.beans.global;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Domain {

	private static final String[] REGEXP = {
		"^(([^.]+)\\.\\w{2,4})$",
		"^(([^.]+)\\.(com|co|org|net)\\.\\w{2})$",
		"^(([^.]+)\\.\\w{2})\\.(com)$",
	};

	private String url;
	private String domain;
	private String key;
	private String ip;
	
	public Domain() {
	}
	
	public Domain(String url) {
		parse(url);
	}

	public Domain parse(String url) {
		url = url == null ? null : url.toLowerCase();
		Domain domain = this;
		if (url == null)
			return domain;
		domain.url = url;
		url = cut(url, true, "www.");
		url = cut(url, true, "http://");
		url = cut(url, true, "https://");
		url = cut(url, false, "/");
		url = cut(url, false, "\\");
		url = cut(url, false, "?");
		url = cut(url, false, "#");
		
		for (int i = 0; i < REGEXP.length; i++) {
			Pattern p = Pattern.compile(REGEXP[i]);
			Matcher m = p.matcher(url);
			if (m.find()) {
				domain.key = m.group(2);
				domain.domain = m.group(1);
				break;
			}
		}
		return domain;
	}
	
	private static String cut(String str, boolean front, String sym) {
		int i = str.indexOf(sym);
		if (i != -1) {
			if (front) {
				i = str.lastIndexOf(sym);
				return str.substring(i + sym.length());
			}
			return str.substring(0, i);
		}
		return str;
	}
	
//	private String match(String str, String regexp, int group) {
//		Pattern p = Pattern.compile(regexp);
//		Matcher m = p.matcher(str);
//		if (m.find())
//			return m.group(group);
//		return null;
//	}

	public String getDomain() {
		return domain;
	}

	public String getKey() {
		return key;
	}
	
	public String getUrl() {
		return url;
	}

	public String getIP() {
		if (domain == null || ip != null)
			return ip;
		return ip = getDomainIP(domain);
	}
	
	public static String getDomainIP(String domain) {
		if (domain == null)
			return null;
		InetAddress address = null;
		try {
			address = InetAddress.getByName(domain);
		} catch (UnknownHostException e) {
			return "---";
		}
		return address.getHostAddress();
	}
	
	@Override
	public String toString() {
		return domain == null ? "-" : ip != null ? domain + "(" + ip + ")" : domain;
	}

	public static void main(String[] args) {
		Domain d = new Domain();
		System.out.println(d.parse("http://hnzhoujunmei.javaeye.com/blog/741213"));
		System.out.println(d.parse("http://www.javaeye.com/blog/741213"));
		System.out.println(d.parse("www.javaeye.com/blog/741213"));
		System.out.println(d.parse("www.javaeye.com"));
		System.out.println(d.parse("javaeye.com"));
	}
}
